package com.yckj.activechicken.business.system.service.impl;

import com.yckj.activechicken.business.hr.mapper.HrEmployeeMapper;
import com.yckj.activechicken.business.hr.model.HrEmployee;
import com.yckj.activechicken.business.system.mapper.SysUserMapper;
import com.yckj.activechicken.business.system.mapper.SysUserPostMapper;
import com.yckj.activechicken.business.system.mapper.SysUserRoleMapper;
import com.yckj.activechicken.business.system.mapper.comp.SysPostMapperComp;
import com.yckj.activechicken.business.system.mapper.comp.SysRoleMapperComp;
import com.yckj.activechicken.business.system.mapper.comp.SysUserMapperComp;
import com.yckj.activechicken.business.system.model.*;
import com.yckj.activechicken.business.system.service.ISysConfigService;
import com.yckj.activechicken.business.system.service.ISysUserService;
import com.yckj.activechicken.common.constant.UserConstants;
import com.yckj.activechicken.common.utils.StringUtils;
import com.yckj.activechicken.common.utils.security.SecurityUtils;
import com.yckj.activechicken.framework.aspectj.lang.annotation.DataScope;
import com.yckj.activechicken.framework.exception.CustomException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * <p>
 * Title:com.yckj.activechicken.business.service.impl
 * </p>
 * <p/>
 * <p>
 * Description: 描述【用户管理业务处理实现类】
 * </p>
 * <p/>
 * <p>
 * Copyright: Copyright (c) 2019
 * </p>
 * <p/>
 * <p>
 * Company: 英才汇硕信息技术有限公司
 * </p>
 *
 * @author zhoujy
 * @version 1.0
 * @created 2020/5/5 14:48
 */
@Service
public class SysUserServiceImpl implements ISysUserService {
    Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysUserMapperComp sysUserMapperComp;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private SysRoleMapperComp sysRoleMapperComp;

    @Autowired
    private SysPostMapperComp sysPostMapperComp;

    @Autowired
    private SysUserPostMapper sysUserPostMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private HrEmployeeMapper hrEmployeeMapper;

    /**
     * 查询所有用户信息
     *
     * @return List用户集合
     */
    @Override
    public List<SysUser> queryUserList() {
        return null;
    }

    /**
     * 通过id查询用户信息
     *
     * @param userId 用户id
     * @return 用户信息
     */
    @Override
    public SysUser queryUserById(Integer userId) {
        return sysUserMapper.selectByPrimaryKey(userId);
    }

    /**
     * 通过用户名查询用户信息
     *
     * @param username
     * @return
     */
    @Override
    public List<SysUser> queryUserByUsername(String username) {
        SysUserExample sysUserExample = new SysUserExample();
        sysUserExample.createCriteria().andUserNameEqualTo(username);
        List<SysUser> sysUserList = sysUserMapper.selectByExample(sysUserExample);
        return sysUserList;
    }

    /**
     * 根据条件分页查询用户列表
     *
     * @param user 用户信息
     * @return
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectUserList(SysUser user) {
        return sysUserMapperComp.selectUserList(user);
    }

    /**
     * 通过用户名查询用户
     *
     * @param userName 用户名
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserByUserName(String userName) {
        SysUser sysUser = sysUserMapperComp.selectUserByUserName(userName);
        List<SysPost> list = sysPostMapperComp.selectPostsByUserName(userName);
        Set<SysPost> set = new HashSet<>(list);
        sysUser.setPosts(set);
        return sysUser;
    }

    /**
     * 通过用户名查询用户信息及员工信息
     * @param userName
     * @return
     */
    @Override
    public List<SysUser> queryUserEmpByUserName(String userName){
        return sysUserMapperComp.selectUserEmpByUserName(userName);
    }

    /**
     * 多条件查询用户信息
     *
     * @param user
     * @return
     */
    @Override
    @DataScope(deptAlias="d", userAlias = "u")
    public Map<String, Object> selectUserByCond(SysUser user) {
        int pageSize = user.getPageSize();
        int pageNum = user.getPageNum();

        int beginNum = 0;
        if (pageNum > 0) {
            beginNum = (pageNum - 1) * pageSize;
        }

        user.setMybeginNum(beginNum);
        user.setMyPageNum(pageSize);
        //pageHelper插件通过以下两个属性来决定是否进行分页处理，如果自定义进行分页处理，必须将其设置为null
        user.setPageSize(null);
        user.setPageNum(null);

        int total = sysUserMapperComp.selectUserByCondCount(user);
        List<SysUser> list = sysUserMapperComp.selectUserByCond(user);
        Map<String, Object> outMap = new HashMap<>();
        outMap.put("total", total);
        outMap.put("list", list);
        return outMap;
    }

    /**
     * 导入用户数据
     *
     * @param userList        用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName        操作用户
     * @return 结果
     */
    @Override
    public String importUser(List<SysUser> userList, Boolean isUpdateSupport, String operName) {
        if (StringUtils.isNull(userList) || userList.size() == 0) {
            throw new CustomException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        String password = configService.selectConfigByKey("sys.user.initPassword");
        Date newDate = new Date();
        for (SysUser user : userList) {
            try {
                // 验证是否存在这个用户
                SysUserExample sysUserExample = new SysUserExample();
                sysUserExample.createCriteria().andUserNameEqualTo(user.getUserName());
                List<SysUser> sysUserList = sysUserMapper.selectByExample(sysUserExample);
                if (StringUtils.isEmpty(sysUserList)) {
                    user.setPassword(SecurityUtils.encryptPassword(password));
                    user.setCreateBy(operName);
                    user.setCreateTime(newDate);
                    user.setUpdateBy(operName);
                    user.setUpdateTime(newDate);
                    this.insertUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 导入成功");
                } else if (isUpdateSupport) {
                    user.setUpdateBy(operName);
                    this.updateUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、账号 " + user.getUserName() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + user.getUserName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new CustomException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    /**
     * 新增保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertUser(SysUser user) {
        //新增员工信息
        HrEmployee hrEmployee = this.userToEmployee(user);
        hrEmployeeMapper.insertSelective(hrEmployee);

        // 新增用户信息
        user.setEmpId(hrEmployee.getEmpId());
        int rows = sysUserMapper.insertSelective(user);
        // 新增用户岗位关联
        insertUserPost(user);
        // 新增用户与角色管理
        insertUserRole(user);
        return rows;
    }

    /**
     * 修改保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateUser(SysUser user) {
        Integer userId = user.getUserId();
        // 删除用户与角色关联
        SysUserRoleExample sysUserRoleExample = new SysUserRoleExample();
        sysUserRoleExample.createCriteria().andUserIdEqualTo(userId);
        sysUserRoleMapper.deleteByExample(sysUserRoleExample);
        // 新增用户与角色关联
        insertUserRole(user);
        // 删除用户与岗位关联
        SysUserPostExample sysUserPostExample = new SysUserPostExample();
        sysUserPostExample.createCriteria().andUserIdEqualTo(userId);
        sysUserPostMapper.deleteByExample(sysUserPostExample);
        // 新增用户与岗位关联
        insertUserPost(user);

        //更新用户员工数据
        HrEmployee hrEmployee = userToEmployee(user);
        hrEmployeeMapper.updateByPrimaryKeySelective(hrEmployee);

        return sysUserMapper.updateByPrimaryKeySelective(user);
    }

    /**
     * 通过用户ID查询用户
     *
     * @param userId 用户ID
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserById(Integer userId) {
        SysUser sysUser = sysUserMapperComp.selectUserById(userId);
        Integer empId = sysUser.getEmpId();
        HrEmployee hrEmployee = hrEmployeeMapper.selectByPrimaryKey(empId);
        return this.empToUser(hrEmployee, sysUser);
    }

    /**
     * 通过User对象中的empId查询员工信息，并将员工信息加入到Sysuser模型中
     *
     * @param sysUser empoId
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserEmpByEmpId(SysUser sysUser) {
        Integer empId = sysUser.getEmpId();
        HrEmployee hrEmployee = hrEmployeeMapper.selectByPrimaryKey(empId);
        return this.empToUser(hrEmployee, sysUser);
    }

    /**
     * 查询集合中每个用户的员工信息
     *
     * @param userList
     * @return
     */
    @Override
    public List<SysUser> queryEmpToUserList(List<SysUser> userList) {
        List<SysUser> outUserList = new ArrayList<>();
        if (StringUtils.isNotEmpty(userList)) {
            for (SysUser sysUser : userList) {
                Integer empId = sysUser.getEmpId();
                HrEmployee hrEmployee = hrEmployeeMapper.selectByPrimaryKey(empId);
                sysUser = this.empToUser(hrEmployee, sysUser);
                outUserList.add(sysUser);
            }
            return outUserList;
        }
        return userList;
    }

    /**
     * 查询用户所属角色组
     *
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserRoleGroup(String userName) {
        List<SysRole> list = sysRoleMapperComp.selectRolesByUserName(userName);
        StringBuffer idsStr = new StringBuffer();
        for (SysRole role : list) {
            idsStr.append(role.getRoleName()).append(",");
        }
        if (StringUtils.isNotEmpty(idsStr.toString())) {
            return idsStr.substring(0, idsStr.length() - 1);
        }
        return idsStr.toString();
    }

    /**
     * 查询用户所属岗位组
     *
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserPostGroup(String userName) {
        List<SysPost> list = sysPostMapperComp.selectPostsByUserName(userName);
        StringBuffer idsStr = new StringBuffer();
        for (SysPost post : list) {
            idsStr.append(post.getPostName()).append(",");
        }
        if (StringUtils.isNotEmpty(idsStr.toString())) {
            return idsStr.substring(0, idsStr.length() - 1);
        }
        return idsStr.toString();
    }

    /**
     * 校验用户名称是否唯一
     *
     * @param userName 用户名称
     * @return 结果
     */
    @Override
    public String checkUserNameUnique(String userName) {
        SysUserExample userExample = new SysUserExample();
        userExample.createCriteria().andUserNameEqualTo(userName);
        int count = (int) sysUserMapper.countByExample(userExample);
        if (count > 0) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验用户是否允许操作
     *
     * @param user 用户信息
     */
    @Override
    public void checkUserAllowed(SysUser user) {
        if (StringUtils.isNotNull(user.getUserId()) && user.isAdmin()) {
            throw new CustomException("不允许操作超级管理员用户");
        }
    }

    /**
     * 批量删除用户信息
     *
     * @param userIds 需要删除的用户ID
     * @return 结果
     */
    @Override
    public int deleteUserByIds(Integer[] userIds) {
        for (Integer userId : userIds) {
            SysUser sysUser = new SysUser();
            sysUser.setUserId(userId);
            checkUserAllowed(sysUser);
        }
        return sysUserMapperComp.deleteUserByIds(userIds);
    }

    /**
     * 通过用户ID删除用户
     *
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    public int deleteUserById(Integer userId) {
        // 删除用户与角色关联
        SysUserRoleExample sysUserRoleExample = new SysUserRoleExample();
        sysUserRoleExample.createCriteria().andUserIdEqualTo(userId);
        sysUserRoleMapper.deleteByExample(sysUserRoleExample);

        // 删除用户与岗位关联
        SysUserPostExample sysUserPostExample = new SysUserPostExample();
        sysUserPostExample.createCriteria().andUserIdEqualTo(userId);
        sysUserPostMapper.deleteByExample(sysUserPostExample);

        return sysUserMapper.deleteByPrimaryKey(userId);
    }

    /**
     * 重置用户密码
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int resetPwd(SysUser user) {
        return sysUserMapper.updateByPrimaryKeySelective(user);
    }

    /**
     * 重置用户密码
     *
     * @param userName 用户名
     * @param password 密码
     * @return 结果
     */
    @Override
    public int resetUserPwd(String userName, String password) {
        return sysUserMapperComp.resetUserPwd(userName, password);
    }

    /**
     * 修改用户头像
     *
     * @param userName 用户名
     * @param avatar   头像地址
     * @return 结果
     */
    @Override
    public boolean updateUserAvatar(String userName, String avatar) {
        return sysUserMapperComp.updateUserAvatar(userName, avatar) > 0;
    }

    /**
     * 修改用户状态
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserStatus(SysUser user) {
        return sysUserMapper.updateByPrimaryKeySelective(user);
    }

    /**
     * 修改用户基本信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserProfile(SysUser user) {
        HrEmployee hrEmployee = this.userToEmployee(user);
        hrEmployeeMapper.updateByPrimaryKeySelective(hrEmployee);
        return sysUserMapper.updateByPrimaryKeySelective(user);
    }

    /**
     * 新增用户岗位信息
     *
     * @param user 用户对象
     */
    private void insertUserPost(SysUser user) {
        Integer[] posts = user.getPostIds();
        if (StringUtils.isNotNull(posts)) {
            // 新增用户与岗位管理
            for (Integer postId : posts) {
                SysUserPost up = new SysUserPost();
                up.setUserId(user.getUserId());
                up.setPostId(postId);
                sysUserPostMapper.insertSelective(up);
            }
        }
    }

    /**
     * 新增用户角色信息
     *
     * @param user 用户对象
     */
    private void insertUserRole(SysUser user) {
        Integer[] roles = user.getRoleIds();
        if (StringUtils.isNotNull(roles)) {
            // 新增用户与角色管理
            for (Integer roleId : roles) {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(user.getUserId());
                ur.setRoleId(roleId);
                sysUserRoleMapper.insertSelective(ur);
            }
        }
    }

    /**
     * 从sysUser中获取HrEmployee的信息
     *
     * @param sysUser
     * @return
     */
    private HrEmployee userToEmployee(SysUser sysUser) {
        HrEmployee hrEmployee = new HrEmployee();
        hrEmployee.setEmpId(sysUser.getEmpId());
        hrEmployee.setName(sysUser.getName());
        hrEmployee.setSex(sysUser.getSex());
        hrEmployee.setIdCard(sysUser.getIdCard());
        hrEmployee.setBirthday(sysUser.getBirthday());
        hrEmployee.setAddress(sysUser.getAddress());
        hrEmployee.setIsMarital(sysUser.getIsMarital());
        hrEmployee.setSpouseCompleteName(sysUser.getSpouseCompleteName());
        hrEmployee.setSpouseBirthday(sysUser.getSpouseBirthday());
        hrEmployee.setChildrenNum(sysUser.getChildrenNum());
        hrEmployee.setMobilePhone(sysUser.getMobilePhone());
        hrEmployee.setEmail(sysUser.getEmail());
        hrEmployee.setWorkEmail(sysUser.getWorkEmail());
        hrEmployee.setWorkPhone(sysUser.getWorkPhone());
        hrEmployee.setWorkLocation(sysUser.getWorkLocation());
        hrEmployee.setContractWarning(sysUser.getContractWarning());
        hrEmployee.setJobTypeId(sysUser.getJobTypeId());
        hrEmployee.setJobResumeId(sysUser.getJobResumeId());
        hrEmployee.setProfTypeId(sysUser.getProfTypeId());
        hrEmployee.setEduResumeId(sysUser.getEduResumeId());
        hrEmployee.setColor(sysUser.getColor());
        hrEmployee.setBadgeId(sysUser.getBadgeId());
        hrEmployee.setCoachName(sysUser.getCoachName());
        hrEmployee.setIsActive(sysUser.getIsActive());
        hrEmployee.setDepartureReason(sysUser.getDepartureReason());
        hrEmployee.setDepartureDescription(sysUser.getDepartureDescription());
        hrEmployee.setCreateBy(sysUser.getCreateBy());
        hrEmployee.setCreateTime(sysUser.getCreateTime());
        hrEmployee.setUpdateBy(sysUser.getUpdateBy());
        hrEmployee.setUpdateTime(sysUser.getUpdateTime());
        return hrEmployee;
    }

    /**
     * 将hrEmployee添加到User模型中去
     *
     * @param hrEmployee
     * @return
     */
    private SysUser empToUser(HrEmployee hrEmployee, SysUser sysUser) {
        sysUser.setEmpId(hrEmployee.getEmpId());
        sysUser.setName(hrEmployee.getName());
        sysUser.setSex(hrEmployee.getSex());
        sysUser.setIdCard(hrEmployee.getIdCard());
        sysUser.setBirthday(hrEmployee.getBirthday());
        sysUser.setAddress(hrEmployee.getAddress());
        sysUser.setIsMarital(hrEmployee.getIsMarital());
        sysUser.setSpouseCompleteName(hrEmployee.getSpouseCompleteName());
        sysUser.setSpouseBirthday(hrEmployee.getSpouseBirthday());
        sysUser.setChildrenNum(hrEmployee.getChildrenNum());
        sysUser.setMobilePhone(hrEmployee.getMobilePhone());
        sysUser.setEmail(hrEmployee.getEmail());
        sysUser.setWorkEmail(hrEmployee.getWorkEmail());
        sysUser.setWorkPhone(hrEmployee.getWorkPhone());
        sysUser.setWorkLocation(hrEmployee.getWorkLocation());
        sysUser.setContractWarning(hrEmployee.getContractWarning());
        sysUser.setJobTypeId(hrEmployee.getJobTypeId());
        sysUser.setJobResumeId(hrEmployee.getJobResumeId());
        sysUser.setProfTypeId(hrEmployee.getProfTypeId());
        sysUser.setEduResumeId(hrEmployee.getEduResumeId());
        sysUser.setColor(hrEmployee.getColor());
        sysUser.setBadgeId(hrEmployee.getBadgeId());
        sysUser.setCoachName(hrEmployee.getCoachName());
        sysUser.setIsActive(hrEmployee.getIsActive());
        sysUser.setDepartureReason(hrEmployee.getDepartureReason());
        sysUser.setDepartureDescription(hrEmployee.getDepartureDescription());
        return sysUser;
    }
}
